package com.ideaction.game.sec;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.annotation.Order;

import com.ideaction.game.utils.IpUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * filter处于最外层筛选,还未进入springmvc的servletdispatcher 粒度最大
 *
 */
@WebFilter(filterName = "ReqFilter", urlPatterns = "/*")
@Order(1)
@Slf4j
public class ServerFilter implements Filter {
	private String headStr = "RequestData=";

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httprequest = (HttpServletRequest) request;
		String method = httprequest.getMethod();
		String contentType = httprequest.getContentType();
		//log.info("contentType:"+contentType);
		// 只接受post
		if (method.equalsIgnoreCase("post")) {
			// 验证post格式
			byte[] head = new byte[headStr.length()];
			int len = request.getInputStream().read(head);
			if (len > 0) {
				String requesthead = new String(head, "UTF-8");
				//requesthead = URLDecoder.decode(requesthead, StandardCharsets.UTF_8.name());
				//body格式内容错误
				if (!headStr.equals(requesthead)) {
					String ip = IpUtils.getClientIp(httprequest);
					log.warn("bad body ip:" + ip + "  content:" + new String(head)
							+ IOUtils.toString(httprequest.getInputStream()));
					return;
				}
			}
			chain.doFilter(request, response);
		} else {
			String ip = IpUtils.getClientIp(httprequest);
			String url = httprequest.getRequestURL().toString();
			if(!url.equals("http://localhost:5001/CheckHealth")){
				log.warn("bad get request! ip:" + ip + " url:" + url+" method:"+method);
			}
		}

	}
}
